package whu.cn.whushare.util;

import android.view.View;
import android.widget.AbsListView;

import com.androidplus.util.ViewMapping;

import java.lang.reflect.Field;

/**
 * 类 名：SetOnClickUtil
 * 功 能：为指定class文件中所声明的域对象设置onClickListener
 */
public class SetOnClickUtil {
	public static void registerOnClick(View.OnClickListener listener) {
		registerOnClick(listener, listener.getClass());
	}

	public static void registerOnClick(View.OnClickListener listener, Class<?> clazz) {
		Field[] fields = clazz.getDeclaredFields();

		ViewMapping viewMapping;
		for (Field field : fields) {
			viewMapping = field.getAnnotation(ViewMapping.class);
			if (viewMapping != null) {
				try {
					field.setAccessible(true);      //取消Java访问权限控制检查
					if (View.class.isAssignableFrom(field.getType())) {     //若field类是一个view类
						View v = (View) field.get(listener);                //获取field中的点击监听器对象listener的值
						if (v != null && !(v instanceof AbsListView)) {
							v.setOnClickListener(listener);
						}
					}
				} catch (Exception e) {
					throw new RuntimeException(field.getName() + " setOnClickListener error : " + e.getMessage());
				}
			}
		}
	}
}
